package com.jichangxiu.framework.action;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jichangxiu.common.constant.ErrorCode;
import com.jichangxiu.common.entity.bo.Result;
import com.jichangxiu.common.entity.bo.SecurityUser;
import com.jichangxiu.common.utils.ServletUtils;
import com.jichangxiu.common.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.annotation.Resource;
import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * BaseAction:
 *
 * @author Jcx
 * @create 2023-04-04 10:13
 */
public class BaseAction {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private TokenUtils tokenUtils;

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为 Date 类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtil.parseDate(text));
            }
        });
    }

    protected <T> Result<T> ok() {
        return Result.ok();
    }

    protected <T> Result<T> ok(String message) {
        return Result.ok(message, null);
    }

    protected <T> Result<T> ok(String message, T t) {
        return Result.ok(message, t);
    }

    protected <T> Result<T> ok(T t) {
        return Result.ok(t);
    }

    protected <T> Result<T> no() {
        return Result.no();
    }

    protected <T> Result<T> no(String message) {
        return Result.no(message, null);
    }

    protected <T> Result<T> no(ErrorCode errorCode) {
        return Result.no(errorCode);
    }

    protected <T> Result<T> toAjax(int rows) {
        return rows > 0 ? ok() : no();
    }

    protected <T> Result<T> toAjax(boolean result) {
        return result ? ok() : no();
    }

    protected String toStr(boolean result) {
        return result ? "操作成功" : "操作失败";
    }

    /**
     * 获取用户缓存信息
     */
    public SecurityUser getSecurityUser() {
        SecurityUser securityUser = ServletUtils.getSecurityUser();
        if (ObjectUtil.isEmpty(securityUser)) {
            securityUser = tokenUtils.getSecurityUser();
        }
        return securityUser;
    }

    /**
     * 获取登录用户id
     */
    public String getUserId() {
        return getSecurityUser().getRecord().getStr("userId");
    }

    /**
     * 获取登录部门id
     */
    public String getDeptId() {
        return getSecurityUser().getRecord().getStr("deptId");
    }

    /**
     * 获取登录用户名
     */
    public String getUsername() {
        return getSecurityUser().getUsername();
    }

}
